<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <!-- 自定义添加任务事件 -->
    <TodoHeader @addTask="addTaskFn" :list='list'></TodoHeader>
    <!-- 将数据传到TodoMain组件 -->
    <!-- 自定义删除任务事件 -->
    <TodoMain :list="list" @delFn="delFun"></TodoMain>
    <TodoFooter :list="showArr" @fun="Fun" @clean="cleanFun"></TodoFooter>
  </section>
</template>

<script>
// 1.0 样式引入
import "./styles/base.css";
import "./styles/index.css";
// 引入组件
import TodoHeader from "./components/todo/TodoHeader.vue";
import TodoMain from "./components/todo/TodoMain.vue";
import TodoFooter from "./components/todo/TodoFooter.vue";

export default {
  data() {
    return {
      // list从浏览器本地取值
      list: JSON.parse(localStorage.getItem("listArr")),
      str: "",
    };
  },
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  methods: {
    // 添加任务事件
    addTaskFn(theTaskName) {
      // console.log(theTaskName);
      let obj = {};
      // 添加id时，首先得先判断数组是否为空
      obj.id =
        this.list.length !== 0 ? this.list[this.list.length - 1].id + 1 : 100;
      obj.name = theTaskName;
      obj.isDone = false;
      // console.log(obj);
      this.list.push(obj);
    },
    // 删除事件
    delFun(id) {
      // console.log(id);
      let index = this.list.findIndex((item) => item.id === id);
      // console.log(index);
      this.list.splice(index, 1);
    },
    // 切换事件
    Fun(a) {
      // 接收组件传来的值a
      //  console.log(a);
      this.str = a;
      // console.log(this.str);
    },
    // 清除已完成
    cleanFun() {
      // console.log(2);
      this.list = this.list.filter((item) => !item.isDone);
    },
  },
  computed: {
    showArr() {
      if (this.str == "yes") {
        return this.list.filter((item) => item.isDone);
      } else if (this.str == "no") {
        return this.list.filter((item) => !item.isDone);
      } else {
        return this.list;
      }
    },
  },
  watch: {
    list: {
      deep: true, //对复杂对象要深度监听
      handler() {
        //只要list发生变化就会执行handler函数
        localStorage.setItem("listArr", JSON.stringify(this.list));
      },
    },
  },
};
</script>